package com.dietmanager.view;

import java.util.ArrayList;
import java.util.Observable;
import java.util.Observer;

import com.dietmanager.datalayer.DataLayer;
import com.dietmanager.model.Exercise;
import com.dietmanager.model.ExerciseModel;
import com.dietmanager.model.FoodModel;
import com.dietmanager.model.Recipe;
import com.dietmanager.model.Workout;
import com.dietmanager.model.javafx.util.RecipeListEntry;
import com.dietmanager.model.javafx.util.WorkoutListEntry;

import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Pos;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;

/**
 * 
 * @author Petar, Danijel
 * @description This class is the view for creating and modifying workouts.
 *              Functions almost the same as AddRecipeView
 */
public class AddWorkoutView extends Observable {

	ArrayList<Observer> observerList = new ArrayList<Observer>();

	// Instance vars
	public Button add, save;
	public ComboBox exerciseWorkoutComboBox;
	public TextField amountTextField, nameTextField, fullCaloriesTextField;
	public VBox addWorkoutView;
	public TableView workoutTable;
	public TableColumn name, calories, minutes;
	public double fullCalories;

	public ObservableList<String> workoutExerciseList = FXCollections
			.observableArrayList();
	private final ObservableList<WorkoutListEntry> data = FXCollections
			.observableArrayList();

	// Main constructor
	public AddWorkoutView() {

		createAddWorkoutView();
	}

	// Method that creates the interface (GUI)
	public void createAddWorkoutView() {

		// TextField for the sum of calories
		HBox sumHbox = new HBox();
		sumHbox.setSpacing(7);
		sumHbox.setAlignment(Pos.CENTER);
		fullCaloriesTextField = new TextField();
		fullCaloriesTextField.setPrefColumnCount(2);
		fullCaloriesTextField.setPromptText("#");
		fullCaloriesTextField.setEditable(false);
		Label fullCalLabel = new Label("Calorie Sum: ");
		fullCalLabel.getStyleClass().add("tLabel");
		sumHbox.getChildren().addAll(fullCalLabel, fullCaloriesTextField);

		// Create the container
		addWorkoutView = new VBox();
		addWorkoutView.setSpacing(10);
		addWorkoutView.getStyleClass().add("addRecipeView");

		// Create the table for food and amount
		workoutTable = new TableView();
		name = new TableColumn("Name");
		calories = new TableColumn("Calories");
		minutes = new TableColumn("Minutes");

		name.setCellValueFactory(new PropertyValueFactory<RecipeListEntry, String>(
				"name"));
		calories.setCellValueFactory(new PropertyValueFactory<RecipeListEntry, String>(
				"calories"));
		minutes.setCellValueFactory(new PropertyValueFactory<RecipeListEntry, String>(
				"minutes"));

		
		/*
		 * calories and repetitions WorkoutListEntry
		 */
		// TODO

		// Table preferences
		workoutTable.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
		workoutTable.getColumns().addAll(name, calories, minutes);
		workoutTable.getStyleClass().add("recipeTable");

		// Create HBox that contains adding elements
		HBox addBar = new HBox();
		addBar.setSpacing(7);
		addBar.setAlignment(Pos.CENTER);
		// Create combobox, textfield, button
		exerciseWorkoutComboBox = new ComboBox(workoutExerciseList);
		exerciseWorkoutComboBox.setValue("Pick an Exercise/Workout");

		workoutTable.setItems(data);

		amountTextField = new TextField();
		amountTextField.setPrefColumnCount(2);
		amountTextField.setPromptText("#N.");

		final Workout w = new Workout("", 0, 0);

		add = new Button("Add Workout");
		add.getStyleClass().add("customButton");
		add.setOnAction(new EventHandler<ActionEvent>() {

			// When add button pressed...
			@Override
			public void handle(ActionEvent event) {
				DataLayer<ArrayList<ExerciseModel>> exerciseDataLayer = new DataLayer<ArrayList<ExerciseModel>>(
						ExerciseModel.class.getName());
				ArrayList<ExerciseModel> exerciseModelArr = exerciseDataLayer
						.readFile();

				ExerciseModel em = null;
				for (ExerciseModel e : exerciseModelArr)

					if (e.getName().equals(
							exerciseWorkoutComboBox.getValue().toString()))
						em = e;
				
				if (em != null) {
					try {
						em.setAmount(Integer.parseInt(amountTextField.getText()
								.toString()));
					} catch (NumberFormatException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					
					System.out.println(em.getName());
					
					w.add((ExerciseModel)em);
					data.add(new WorkoutListEntry(em.getName(), em
							.getCalories() + "", em.getMinutes() + "", ""));
				}// end of IF

				// When finished, update the sum of calories
				setCaloriesSum();
			}

		}); // end of add button action

		// add everything to hbox
		addBar.getChildren().addAll(exerciseWorkoutComboBox, amountTextField,
				add);

		// Bottom textfield and button
		HBox bottomItems = new HBox(); // just to keep it more clear and easier
		// to manipulate
		bottomItems.setSpacing(7);
		bottomItems.setAlignment(Pos.CENTER);

		nameTextField = new TextField();
		nameTextField.setPromptText("Exercise/Workout Name");
		save = new Button("Save");
		save.setOnAction(new EventHandler<ActionEvent>() {

			@Override
			public void handle(ActionEvent event) {
				w.setName(nameTextField.getText().toString());
				notifyObservers(w);

				data.clear();
			}

		}); // end of save button action
		bottomItems.getChildren().addAll(nameTextField, save);

		// Add everything to GridPane
		addWorkoutView.getChildren().addAll(workoutTable, sumHbox, addBar,
				bottomItems);

		return;
	}

	// SETer for the sum of calories
	public void setCaloriesSum() {
		double sum = 0;
		for (int i = 0; i < data.size(); i++) {
			sum = sum + Double.parseDouble(data.get(i).getCalories());
		}
		fullCaloriesTextField.setText(Double.toString(sum));
	}

	// GETer for the view
	public VBox getAddWorkoutView() {
		return addWorkoutView;
	}

	public void updateExerciseList(ArrayList<ExerciseModel> em) {
		workoutExerciseList.clear();

		if (em != null)
			for (ExerciseModel e : em)
				workoutExerciseList.add(e.getName());
	}

	public void addObserver(Observer o) {
		observerList.add(o);
	}

	public void addObserverCollection(ArrayList<Observer> obs) {
		observerList.clear();
		observerList = obs;
	}

	public void notifyObservers(Object o) {
		for (Observer ob : observerList)
			ob.update(this, o);
	}
}
